package com.example.demo.controller;

import com.example.demo.dto.QuestionDTO;
import com.example.demo.mapper.QuestionMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.QuestionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author redjava
 * @create 2021-07-20 10:17
 */
@Controller
public class IndexController {
    @Autowired
    private QuestionService questionService;
    @Autowired
    private QuestionMapper questionMapper;

    @GetMapping("/")
    public String index() {
        return "index";
    }

    @PostMapping("/toPage")
    @ResponseBody
    public PageInfo<QuestionDTO> page(@RequestParam(name = "page", defaultValue = "1") Integer page) {
        //查询总记录数
        int count = questionMapper.count();
        int totalPages = 0;
        if (count % 5 == 0) {
            totalPages = count / 5;
        } else {
            totalPages = count / 5 + 1;
        }

        PageHelper.startPage(page, 5);
        List<QuestionDTO> questionDTOS = questionService.list();
        PageInfo<QuestionDTO> pageInfo = new PageInfo<>(questionDTOS);
        pageInfo.setPages(totalPages);
        return pageInfo;
    }
}
